<?php

namespace App\Admin\Controllers;

use App\Models\Role;
use App\Models\User;
use function foo\func;
use Illuminate\Http\Request;
use Encore\Admin\Controllers\RoleController as BaseController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Row;
use Encore\Admin\Layout\Column;

class RoleController extends BaseController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '角色管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $roleModel = config('admin.database.roles_model');

        $grid = new Grid(new $roleModel());
        $grid->model()->orderBy('type', 'desc');

        $grid->column('id', 'ID')->sortable();
        $grid->column('slug', trans('admin.slug'));
        $grid->column('name', trans('admin.name'));

        $grid->column('type', '角色类型')->label([
            '系统类角色' => 'warning',
            '机构类角色' => 'success',
            '业务类角色' => 'primary',
        ])->sortable();

        $grid->column('permissions', trans('admin.permission'))->pluck('name')->label();

        $grid->column('created_at', trans('admin.created_at'));
        $grid->column('updated_at', trans('admin.updated_at'));

        $grid->actions(function (Grid\Displayers\Actions $actions) {
            if ($actions->row->slug == '系统管理员') {
                $actions->disableDelete();
            }
        });

        $grid->tools(function (Grid\Tools $tools) {
            $tools->batch(function (Grid\Tools\BatchActions $actions) {
                $actions->disableDelete();
            });
        });


        $grid->filter(function ($filter) {
            $filter->column(1/2, function ($filter) {
                $filter->disableIdFilter();
                $filter->like('name', "角色名称");
            });
            $filter->column(1/2, function ($filter){
                $filter->equal('type','角色类型')->select([
                    '系统类角色' => '系统类角色',
                    '机构类角色' => '机构类角色',
                    '业务类角色' => '业务类角色',
                ]);
            });

        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $roleModel = config('admin.database.roles_model');

        $show = new Show($roleModel::findOrFail($id));

        $show->field('id', 'ID');
        $show->field('slug', trans('admin.slug'));
        $show->field('name', trans('admin.name'));
        $show->field('type', '角色类型');
        $show->field('permissions', trans('admin.permissions'))->as(function ($permission) {
            return $permission->pluck('name');
        })->label();
        $show->field('created_at', trans('admin.created_at'));
        $show->field('updated_at', trans('admin.updated_at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    public function form()
    {
        $permissionModel = config('admin.database.permissions_model');
        $roleModel = config('admin.database.roles_model');

        $form = new Form(new $roleModel());

        $form->display('id', 'ID');

        $form->text('slug', trans('admin.slug'))->rules('required');
        $form->text('name', trans('admin.name'))->rules('required');
        $form->select('type', '角色类型')->options([
            '系统类角色' => '系统类角色',
            '机构类角色' => '机构类角色',
            '业务类角色' => '业务类角色',
        ]);
        $form->listbox('permissions', trans('admin.permissions'))->options($permissionModel::all()->pluck('name', 'id'));

        $form->display('created_at', trans('admin.created_at'));
        $form->display('updated_at', trans('admin.updated_at'));

        return $form;
    }

    public function businessRoleManage(Request $request,Content $content)
    {
        $user = Admin::user();

        return Admin::content(function (Content $content) use ($request,$user) {
            $content->header('机构人员管理');
            $content->description('机构人员管理');

            $content->row(function (Row $row) use ($request,$user){
                $row->column(6, function (Column $column) use ($request,$user){
                    $grid = new Grid(new User());
                    $grid->model()->where('department_id', '=', $user->department_id);
                    $grid->column('id', 'ID')->sortable();
                    $grid->column('name', trans('admin.name'));
                    $grid->column('roles', trans('admin.roles'))->display(function () {
                        $roles = $this->roles()->orderBy('type', 'desc')->get();
                        $contentStr = '';
                        $count = 0;
                        foreach ($roles as $role) {
                            if ($role->type == '系统类角色') {
                                $contentStr = $contentStr . '<span class="label label-warning" style="display: inline-block;margin-top: 3px;padding: 5px 3px
;">' . $role->name . '</span>&nbsp;';
                            } else if ($role->type == '机构类角色') {
                                $contentStr = $contentStr . '<span class="label label-info" style="display: inline-block;margin-top: 3px;padding: 5px 3px
;">' . $role->name . '</span>&nbsp;';
                            } else {
                                $contentStr = $contentStr . '<span class="label label-success" style="display: inline-block;margin-top: 3px;padding: 5px 3px
;">' . $role->name . '</span>&nbsp;';
                            }
                            $count++;
                            if ($count > 3) {
                                $contentStr = $contentStr . '<br/>';
                                $count = 0;
                            }
                        }
                        return $contentStr;
                    });
                    $grid->column('operate','操作')->display(function () {
                        return '<a href = "/admin/portrait/business_role_form/'.$this->id.'/edit" class="btn btn-sm btn-success import-post"><i class="fa fa-pencil"></i>编辑</a>';
                    });
                    $grid->disableActions();

                    // 去掉批量操作
                    $grid->batchActions(function ($batch) {
                        $batch->disableDelete();
                    });
                    // 去掉创建操作
                    $grid->disableCreateButton();

                    $column->row($grid);
                });
                if ($request->id != null){
                    $row->column(6, function (Column $column) use ($request){
                        if ($request->id != null) {
                            $user = User::find($request->id);
                        }else{
                            $user = new User();
                        }
                        $form = new \Encore\Admin\Widgets\Form($user);
                        $form->action('/admin/portrait/business_role_manage');
                        $form->method('post');

                        $form->display('id', '用户ID')->default($request->id);
                        $form->hidden('id')->default($request->id);

                        $form->display('name', '用户名称');

                        $ids = $user->roles()->where('type', '=', '业务类角色')->pluck('id');
                        $form->multipleSelect('role_ids','负责业务')->value($ids->toArray())->options(Role::where('type','=','业务类角色')->pluck('name','id'));   //用户可以选择机构下所有用户

                        $form->hidden('_token')->default(csrf_token());

                        $column->append((new Box("修改员工信息", $form))->style('success'));
                    });
                }
            });
        });
    }
    public function businessRoleSave(Request $request)
    {
        $user = User::find($request->id);
        $role_ids = $request->role_ids;
        array_pop($role_ids);

        $system_department_ids = $user->roles()->where('type', '!=', '业务类角色')->pluck('id as text')->toArray();
        $role_ids = array_merge($role_ids, $system_department_ids);
        //dd($role_ids);
        $user->roles()->sync($role_ids);

        return redirect(route('role.business_role_form'));
    }
}
